package com.person.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.person.mapper.ContactsMapper;
import com.person.mapper.DepartmentMapper;
import com.person.mapper.UserMapper;
import com.person.model.dto.DepartmentDto;
import com.person.model.entity.Contacts;
import com.person.model.entity.Department;
import com.person.model.entity.User;
import com.person.service.BasicSettingsService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BasicSettingsServiceImpl implements BasicSettingsService {

    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private ContactsMapper contactsMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public DepartmentDto getBasicSettingsByUserId(int userId) {
        DepartmentDto departmentDto = new DepartmentDto();
        User user = userMapper.selectById(userId);
        departmentDto.setUser(user);
        Department department = departmentMapper.selectById(user.getDepartmentId());
        BeanUtils.copyProperties(department, departmentDto);
        LambdaQueryWrapper<Contacts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Contacts::getDepartmentId, user.getDepartmentId());
        List<Contacts> contactList = contactsMapper.selectList(queryWrapper);
        if (!contactList.isEmpty()) {
            departmentDto.setContactsList(contactList);
        }
        return departmentDto;
    }

    @Override
    public void updateBasicSetting(DepartmentDto departmentDto) {
        Department department = new Department();
        BeanUtils.copyProperties(departmentDto, department);
        departmentMapper.updateById(department);
        Integer departmentId = departmentDto.getId();
        LambdaQueryWrapper<Contacts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Contacts::getDepartmentId, departmentId);
        List<Contacts> contactsDbList = contactsMapper.selectList(queryWrapper);
        contactsMapper.delete(queryWrapper);
        List<Contacts> contactsList = departmentDto.getContactsList();
        for (int i = 0; i < contactsList.size(); i++) {
            Contacts contacts = contactsList.get(i);
            if (contactsDbList.size() > i) {
                contacts.setId(contactsDbList.get(i).getId());
            }
            contacts.setDepartmentId(departmentId);
            contactsMapper.insert(contacts);
        }
    }
}
